package com.dfrz.bookstore.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 作者：wangmaokang
 * 日期: 2021/5/17 10:06
 * 描述:
 */
public class JdbcUtils {
    // 配置文件的默认配置！要求你必须给出c3p0-config.xml！！！
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    /**
     * 使用连接池返回一个连接对象
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 返回连接池对象！
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    public static void close(Connection connection, Statement statement, ResultSet resultset) throws SQLException {

        if (resultset!=null){
            resultset.close();
//            System.out.println("resultset关闭");
        }

        if (statement!=null){
            try {
                statement.close();
//                System.out.println("statement关闭");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection!=null){
            try {
                connection.close();
//                System.out.println("connection关闭成功");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
